package com.example.thread.d9CompletableFuture2.d6异步任务的异常处理;

import com.example.thread.d9CompletableFuture2.CommonUtils;

import java.util.concurrent.CompletableFuture;

/**
 * handle()用来恢复回调链中的一次特定的异常，回调链恢复后可以进一步向下传递
 * CompletableFuture<R> handle(BiFunction<T,Throable,R> fn)
 */
public class d4_HandleDemo {
    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
//            int r = 1 / 0;
            return "result";
        }).handle((result, ex) -> {
            if (ex != null) {
                CommonUtils.printThreadLog("出现了异常");
                return "Unkown";
            }
            return result;
        }).thenApply(result -> {
            String str = null;
            int length = str.length();

            return result + " result2";
        }).handle((result,ex)-> {
            if (ex != null) {
                CommonUtils.printThreadLog("出现了异常");
                return "Unkown2";
            }
            return result;
        });

        CommonUtils.printThreadLog("main continuous");
        System.out.println("ret："+ future.join());
        CommonUtils.printThreadLog("main end");

        /**
         * CompletableFuture<R> exceptionlly(Function<Throwable,R> fn)
         * CompletableFuture<R> exceptionllyAsync(Function<Throwable,R> fn)  // jdk 17+
         * CompletableFuture<R> exceptionllyAsync(Function<Throwable,R> fn,Executor executor) // jdk 17+
         *
         * CompletableFuture<R> handle(BiFunction<T,Throwable,R> fn)
         * CompletableFuture<R> handleAsync(BiFunction<T,Throwable,R> fn)
         * CompletableFuture<R> handleAsync(BiFunction<T,Throwable,R> fn,Executor executor)
         */
    }
}
